<template>
  <div :style="{ ...coreStyle.marginSame(8) }">
    <a-card>
      <a-form ref="filesFormQueryRef" :model="filesFormQueryModel" labelAlign="left" layout="vertical" :style="{ ...coreStyle.marginBottom(10) }">
        <a-row :gutter="16" v-show="!filesFormQueryVisible">
          <a-col :span="8">
            <a-form-item :style="{ ...coreStyle.marginBottom(-8) }">
              <a-input-search v-model:value="filesFormQueryModel.keySearchVo" placeholder="关键字搜索" :disabled="filesFormQuerySubmitting" @search="filesFormQuerySearch" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item :style="{ ...coreStyle.marginBottom(-8) }">
              <Dict v-model="filesFormQueryModel.fileModule" dictKey="fileModuleSearch" formItemName="fileModule" @change="filesFileModuleDictSelectChange" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-button type="link" :style="{ ...coreStyle.floatRight }" @click="filesFormQueryUpDown">
              展开
              <CoreIcon icon="akar-icons:chevron-down" :size="14" />
            </a-button>
          </a-col>
        </a-row>
        <a-row :gutter="16" v-show="filesFormQueryVisible">
          <a-col :span="8">
            <a-form-item>
              <a-input-search v-model:value="filesFormQueryModel.keySearchVo" placeholder="关键字搜索" :disabled="filesFormQuerySubmitting" @search="filesFormQuerySearch" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item>
              <Dict v-model="filesFormQueryModel.fileModule" dictKey="fileModuleSearch" formItemName="fileModule" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
          </a-col>
          <!-- <a-col :span="8">
            <a-form-item label="文件模块">
              <a-input v-model:value="filesFormQueryModel.fileModuleAndLike" placeholder="输入文件模块" />
            </a-form-item>
          </a-col> -->
          <a-col :span="8">
            <a-form-item label="文件名称">
              <a-input v-model:value="filesFormQueryModel.fileNameAndLike" placeholder="输入文件名称" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="文件地址">
              <a-input v-model:value="filesFormQueryModel.fileUrlAndLike" placeholder="输入文件地址" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="上传时间">
              <!-- <a-input-number v-model:value="filesFormQueryModel.uploadTimes" :style="{ ...coreStyle.width('100%') }" /> -->
              <DateUnixTimeRange v-model:startDate="filesFormQueryModel.uploadTimesStart" v-model:endDate="filesFormQueryModel.uploadTimesEnd" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-space :style="{ ...coreStyle.floatRight }">
              <a-button @click="filesFormQueryReset">
                <CoreIcon icon="ant-design:clear-outlined" :size="14" />
                重置
              </a-button>
              <a-button type="primary" ghost :loading="filesFormQuerySubmitting" @click="filesFormQuerySearch">
                <CoreIcon icon="ant-design:search-outlined" :size="14" />
                查询
              </a-button>
              <a-button type="link" @click="filesFormQueryUpDown">
                收起
                <CoreIcon icon="akar-icons:chevron-up" :size="14" />
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
      <a-space>
        <!-- <a-button type="primary" ghost @click="filesAdd">
          <CoreIcon icon="carbon:add-alt" :size="14" />
          新增
        </a-button>
        <a-button type="dashed" @click="filesUpdate" v-if="filesListSelectLength === 1">
          <CoreIcon icon="ri:brush-line" :size="14" />
          修改
        </a-button> -->
        <a-popconfirm title="确认删除？" placement="bottom" :disabled="filesDeleteDisabled" @confirm="filesDelete">
          <a-button type="dashed" :disabled="filesDeleteDisabled" danger>
            <CoreIcon icon="jam:delete" :size="14" />
            删除
          </a-button>
        </a-popconfirm>
        <!-- <a-button @click="filesDetailInfo" v-if="filesListSelectLength === 1">
          <CoreIcon icon="heroicons-outline:light-bulb" :size="14" />
          详情
        </a-button> -->
      </a-space>
      <a-space :style="{ ...coreStyle.floatRight }">
        <a-button type="link" shape="circle" @click="filesListGetDataSet">
          <CoreIcon icon="ci:refresh" :size="22" />
        </a-button>
      </a-space>
      <a-table
        rowKey="id"
        :columns="filesListColumns"
        :data-source="filesListDataSet"
        :loading="filesListLoading"
        :pagination="false"
        bordered
        :row-selection="{ fixed: true, selectedRowKeys: filesListSelectedRowKeys, onChange: filesListRowOnChange }"
        :scroll="{ x: '100%', y: 550 }"
        :style="{ ...coreStyle.marginTop(10) }"
      >
        <template #fileNameTitle>
          <span>文件名称<a-tag color="orange" :style="{ 'line-height': '19px', ...coreStyle.marginLeft(8) }">点击标签查看文件</a-tag></span>
        </template>
        <template #fileUrlTitle>
          <span>文件地址<a-tag color="orange" :style="{ 'line-height': '19px', ...coreStyle.marginLeft(8) }">点击标签复制文件地址</a-tag></span>
        </template>
        <template #fileModuleData="{ text }">
          <span>{{ coreToolStore.getDictDisplayName('fileModuleSearch', text) }}</span>
        </template>
        <template #fileNameData="{ text, record }">
          <a><a-tag color="cyan" :style="{ 'line-height': '19px' }" @click="filesListFileNameClick(record.fileUrl)">{{ text }}</a-tag></a>
        </template>
        <template #fileUrlData="{ text }">
          <!-- <a><a-tag color="purple" :style="{ 'line-height': '19px' } " v-clipboard="text" v-clipboard:success="filesListFileUrlCopySuccess" v-clipboard:error="filesListFileUrlCopyError">{{ text }}</a-tag></a> -->
          <a><a-tag color="purple" :style="{ 'line-height': '19px' } " @click="filesListFileUrlClick(text)">{{ text }}</a-tag></a>
        </template>
        <template #uploadTimesData="{ text }">
          <span>{{ new Date(text).format() }}</span>
        </template>
      </a-table>
      <a-pagination
        v-model:current="filesListDataPage"
        v-model:pageSize="filesListDataRows"
        :total="filesListDataCount"
        show-size-changer
        show-quick-jumper
        :page-size-options="[ ...coreStyle.antdPaginationPageSizeOptions ]"
        :show-total="(total, range) => coreStyle.antdPaginationShowTotal(total, range)"
        :style="{ ...coreStyle.marginTop(10), ...coreStyle.textAlignCenter }"
        @change="filesListPaginationChange"
        @showSizeChange="filesListPaginationShowSizeChange"
        v-if="filesListPaginationVisible"
      >
      </a-pagination>
      <p :style="{ ...coreStyle.marginTop(14), ...coreStyle.marginBottom(6), ...coreStyle.textAlignCenter }" v-if="!filesListPaginationVisible">
        {{ coreStyle.antdPaginationShowTotal(filesListDataCount) }}
      </p>
    </a-card>
    <a-drawer
      v-model:visible="filesEditDrawerVisible"
      title="编辑文件信息"
      placement="right"
      :closable="false"
      :width="'40%'"
      :header-style="{ ...coreStyle.antdDrawerHeader }"
      :body-style="{ ...coreStyle.margin(50, 0, 30, 0) }"
      @close="filesEditDrawerOnClose"
    >
      <a-form ref="filesFormRef" :model="filesFormModel" :rules="filesFormRules" labelAlign="left" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="文件模块" name="fileModule">
              <a-input v-model:value="filesFormModel.fileModule" placeholder="输入文件模块" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="文件名称" name="fileName">
              <a-input v-model:value="filesFormModel.fileName" placeholder="输入文件名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="文件地址" name="fileUrl">
              <a-input v-model:value="filesFormModel.fileUrl" placeholder="输入文件地址" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="上传时间" name="uploadTimes">
              <a-input-number v-model:value="filesFormModel.uploadTimes" :style="{ ...coreStyle.width('100%') }" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div :style="{ ...coreStyle.antdDrawerFooter }">
        <a-space>
          <a-button @click="filesFormReset">
            <CoreIcon icon="ant-design:clear-outlined" :size="14" />
            重置
          </a-button>
          <a-button type="primary" ghost :loading="filesFormSaveSubmitting" @click="filesFormNextAdd">
            <CoreIcon icon="tabler:player-track-next" :size="14" />
            继续录入
          </a-button>
          <a-button type="primary" ghost :loading="filesFormSaveSubmitting" @click="filesFormSave">
            <CoreIcon icon="ant-design:save-outlined" :size="14" />
            保存
          </a-button>
        </a-space>
      </div>
    </a-drawer>
    <a-drawer
      v-model:visible="filesDetailDrawerVisible"
      title="文件详细信息"
      placement="right"
      :closable="false"
      :width="'40%'"
      :header-style="{ ...coreStyle.antdDrawerHeader }"
      :body-style="{ ...coreStyle.margin(50, 0, 30, 0) }"
    >
      <a-space direction="vertical" :size="20" :style="{ ...coreStyle.width('100%') }">
        <a-descriptions title="基础信息" :column="3" bordered>
          <a-descriptions-item label="文件模块" :span="1">{{ filesDetailModel.fileModule }}</a-descriptions-item>
          <a-descriptions-item label="文件名称" :span="1">{{ filesDetailModel.fileName }}</a-descriptions-item>
          <a-descriptions-item label="文件地址" :span="1">{{ filesDetailModel.fileUrl }}</a-descriptions-item>
          <a-descriptions-item label="上传时间" :span="1">{{ filesDetailModel.uploadTimes }}</a-descriptions-item>
        </a-descriptions>
      </a-space>
      <div :style="{ ...coreStyle.antdDrawerFooter }">
        <a-space>
          <a-button type="dashed" @click="filesDetailUpdate">
            <CoreIcon icon="ri:brush-line" :size="14" />
            修改
          </a-button>
        </a-space>
      </div>
    </a-drawer>
  </div>
</template>

<script lang="ts">
import { Options, Vue } from 'vue-class-component'
import { mapStores } from 'pinia'
import { useCoreToolStore } from '/@/store/modules/cn/core/tool/coreToolStore'
import type { Res } from '/@/tool/Res'
import type { Param } from '/@/tool/Param'

import { useFilesStore } from '/@/store/modules/cn/core/dirs/filesStore'

import type { Files } from '/@/model/cn/core/dirs/eo/Files'
import { toFiles } from '/@/model/cn/core/dirs/eo/Files'

import type { FilesQO } from '/@/model/cn/core/dirs/qo/FilesQO'
import { toFilesQO } from '/@/model/cn/core/dirs/qo/FilesQO'

import type { FilesVO } from '/@/model/cn/core/dirs/vo/FilesVO'
import { toFilesVO } from '/@/model/cn/core/dirs/vo/FilesVO'

@Options({
  name: 'CoreDirs',
  components: {
  },
  computed: {
    ...mapStores(useCoreToolStore, useFilesStore),
  },
})
export default class CoreDirs extends Vue {

  filesListDataSet: Array<FilesVO> = []

  filesListColumns: Array<object> = [
    {
      title: '文件模块',
      dataIndex: 'fileModule',
      align: 'center',
      slots: { customRender: 'fileModuleData' },
      // ellipsis: true,
      width: 200,
    },
    {
      // title: '文件名称',
      dataIndex: 'fileName',
      align: 'center',
      slots: { title: 'fileNameTitle', customRender: 'fileNameData' },
      ellipsis: true,
      width: 400,
    },
    {
      // title: '文件地址',
      dataIndex: 'fileUrl',
      align: 'center',
      slots: { title: 'fileUrlTitle', customRender: 'fileUrlData' },
      ellipsis: true,
      // width: 200,
    },
    {
      title: '上传时间',
      dataIndex: 'uploadTimes',
      align: 'center',
      slots: { customRender: 'uploadTimesData' },
      // ellipsis: true,
      width: 200,
    },
  ]

  filesListLoading: boolean = false

  filesListSelectedRowKeys: string[] = []

  filesListSelectData: Array<FilesVO> = []

  filesListSelectLength: number = 0

  filesListSelectCurrentRowIndex: number = -1

  filesListSelectCurrentRowData: FilesVO = toFilesVO()

  filesListPaginationVisible: boolean = true

  filesListDataPage: number = 1

  filesListDataRows: number = 10

  filesListDataCount: number = 0

  filesListRowOnChange(selectedRowKeys, selectedRows) {
    this.filesListSelectedRowKeys = [ ...selectedRowKeys ]
    this.filesListSelectData = [ ...selectedRows ]
    this.filesListSelectLength = selectedRows.length
  }

  filesListCustomRow(record, index) {
    return {
      'class': index === this.filesListSelectCurrentRowIndex ? 'ant-table-row-selected' : '',
      onClick: (event) => {
        this.filesListSelectCurrentRowIndex = index
        this.filesListSelectCurrentRowData = { ...record }
        let selectedRowKeys = [ ...this.filesListSelectedRowKeys ]
        let selectedRows = [ ...this.filesListSelectData ]
        if (selectedRowKeys.includes(record.id)) {
          this.filesListRowOnChange([ ...selectedRowKeys.filter(eo => { return eo !== record.id }) ], [ ...selectedRows.filter(eo => { return eo.id !== record.id }) ])
        } else {
          selectedRowKeys.push(record.id)
          selectedRows.push(record)
          this.filesListRowOnChange([ ...new Set(selectedRowKeys) ], [ ...new Set(selectedRows) ])
        }
      },
      onDblclick: (event) => {
        this.filesStore.pkVo(this.$toParam<FilesQO>({ id: this.filesListSelectCurrentRowData.id } as FilesQO)).then((res: Res<FilesVO>) => {
          if (res.succ) {
            this.filesDetailModel = { ...res.data[0] }
            this.filesDetailDrawerVisible = true
          } else {
            this.$message.error(res.msg, 6)
          }
        })
      },
    }
  }

  filesListGetDataSet() {
    this.filesListLoading = true
    this.filesListRowOnChange([], [])
    this.filesListSelectCurrentRowIndex = -1
    this.filesListSelectCurrentRowData = toFilesVO()
    this.filesStore.pagingVo(this.$toParam<FilesQO>({ uploadTimesDesc: 'y' } as FilesQO, this.filesListDataPage, this.filesListDataRows)).then((res: Res<FilesVO>) => {
      if (res.succ) {
        this.filesListPaginationVisible = true
        this.filesListDataSet = [ ...res.data ]
        this.filesListDataCount = res.count
        setTimeout(() => { this.filesListLoading = false }, 500)
      } else {
        this.$message.error(res.msg, 6)
        setTimeout(() => { this.filesListLoading = false }, 500)
      }
    }).catch(err => {
      setTimeout(() => { this.filesListLoading = false }, 500)
    })
  }

  filesListPaginationChange() {
    this.filesListGetDataSet()
  }

  filesListPaginationShowSizeChange() {
    this.filesListGetDataSet()
  }

  filesListFileNameClick(fileUrl) {
    window.open(this.coreToolStore.getFileFullUrl(fileUrl), '_blank')
  }

  filesListFileUrlClick(value) {
    this.$vclipboard(value).then(e => {
      this.$message.success('文件地址复制成功！', 1)
    }).catch(err => {
      this.$message.error('文件地址复制失败！', 1)
    })
  }

  filesListFileUrlCopySuccess() {
    this.$message.success('文件地址复制成功！', 1)
  }

  filesListFileUrlCopyError() {
    this.$message.error('文件地址复制失败！', 1)
  }

  filesFormQueryVisible: boolean = false

  filesFormQuerySubmitting: boolean = false

  filesFormQueryModel: FilesQO = toFilesQO()

  filesFormQueryUpDown() {
    this.filesFormQueryVisible = !this.filesFormQueryVisible
  }

  filesFormQueryReset() {
    if (this.$refs.filesFormQueryRef) {
      this.$refs.filesFormQueryRef.resetFields()
      this.filesFormQueryModel = toFilesQO()
    }
  }

  filesFormQuerySearch() {
    this.filesFormQuerySubmitting = true
    this.filesListLoading = true
    this.filesListRowOnChange([], [])
    this.filesListSelectCurrentRowIndex = -1
    this.filesListSelectCurrentRowData = toFilesVO()
    this.filesStore.queryVo(this.$toParam<FilesQO>(this.$toSearch({ ...this.filesFormQueryModel }))).then((res: Res<FilesVO>) => {
      if (res.succ) {
        this.filesListPaginationVisible = false
        this.filesListDataSet = [ ...res.data ]
        this.filesListDataCount = res.count
        setTimeout(() => { this.filesFormQuerySubmitting = false }, 5000)
        setTimeout(() => { this.filesListLoading = false }, 500)
      } else {
        this.$message.error(res.msg, 6)
        setTimeout(() => { this.filesFormQuerySubmitting = false }, 5000)
        setTimeout(() => { this.filesListLoading = false }, 500)
      }
    }).catch(err => {
      setTimeout(() => { this.filesFormQuerySubmitting = false }, 5000)
      setTimeout(() => { this.filesListLoading = false }, 500)
    })
  }

  filesFileModuleDictSelectChange(value) {
    this.filesFormQuerySearch()
  }

  filesEditDrawerVisible: boolean = false

  filesFormSaveSubmitting: boolean = false

  filesFormSaveContinue: boolean = false

  filesFormModel: Files = toFiles()

  filesFormRules: object = {
    // fileModule: [
    //   { type: 'string', required: true, message: '文件模块不能为空！', trigger: ['change', 'blur'] },
    // ],
    // fileName: [
    //   { type: 'string', required: true, message: '文件名称不能为空！', trigger: ['change', 'blur'] },
    // ],
    // fileUrl: [
    //   { type: 'string', required: true, message: '文件地址不能为空！', trigger: ['change', 'blur'] },
    // ],
    // uploadTimes: [
    //   { type: 'number', required: true, message: '上传时间不能为空！', trigger: ['change', 'blur'] },
    // ],
  }

  filesFormReset() {
    if (this.$refs.filesFormRef) {
      this.$refs.filesFormRef.resetFields()
      this.filesFormModel = toFiles()
    }
  }

  filesFormSubmit() {
    this.filesFormSaveSubmitting = true
    this.$refs.filesFormRef.validate().then(() => {
      if (this.filesFormModel.id) {
        this.filesStore.update(this.$toParam<Files>(this.filesFormModel)).then((res: Res<Files>) => {
          if (res.succ) {
            this.$message.success(res.msg, 3)
            this.filesFormReset()
            this.filesFormSaveSubmitting = false
            if (!this.filesFormSaveContinue) {
              this.filesEditDrawerVisible = false
              this.filesListGetDataSet()
            }
          } else {
            this.$message.error(res.msg, 6)
            setTimeout(() => { this.filesFormSaveSubmitting = false }, 3000)
          }
        }).catch(err => {
          setTimeout(() => { this.filesFormSaveSubmitting = false }, 3000)
        })
      } else {
        this.filesStore.save(this.$toParam<Files>(this.filesFormModel)).then((res: Res<Files>) => {
          if (res.succ) {
            this.$message.success(res.msg, 3)
            this.filesFormReset()
            this.filesFormSaveSubmitting = false
            if (!this.filesFormSaveContinue) {
              this.filesEditDrawerVisible = false
              this.filesListGetDataSet()
            }
          } else {
            this.$message.error(res.msg, 6)
            setTimeout(() => { this.filesFormSaveSubmitting = false }, 3000)
          }
        }).catch(err => {
          setTimeout(() => { this.filesFormSaveSubmitting = false }, 3000)
        })
      }
    }).catch(() => {
      setTimeout(() => { this.filesFormSaveSubmitting = false }, 3000)
    })
  }

  filesFormSave() {
    this.filesFormSaveContinue = false
    this.filesFormSubmit()
  }

  filesFormNextAdd() {
    this.filesFormSaveContinue = true
    this.filesFormSubmit()
  }

  filesAdd() {
    if (this.filesFormModel.id) {
      this.filesFormReset()
    }
    this.filesEditDrawerVisible = true
  }

  filesUpdate() {
    this.filesStore.pk(this.$toParam<FilesQO>({ id: this.filesListSelectData[0].id } as FilesQO)).then((res: Res<Files>) => {
      if (res.succ) {
        this.filesFormReset()
        this.filesFormModel = { ...res.data[0] }
        this.filesEditDrawerVisible = true
      } else {
        this.$message.error(res.msg, 6)
      }
    })
  }

  filesEditDrawerOnClose() {
    if (this.filesFormSaveContinue) {
      this.filesFormSaveContinue = false
      this.filesListGetDataSet()
    }
  }

  filesDelete() {
    let param: Array<Files> = []
    this.filesListSelectData.forEach((eo: FilesVO) => {
      param.push({ id: eo.id } as Files)
    })
    this.filesStore.removeBatch(this.$toParam<Files>(param)).then((res: Res<Files>) => {
      if (res.succ) {
        this.$message.success(res.msg, 3)
        this.filesListGetDataSet()
      } else {
        this.$message.error(res.msg, 6)
      }
    })
  }

  get filesDeleteDisabled() {
    return this.filesListSelectLength > 0 ? false : true
  }

  filesDetailDrawerVisible: boolean = false

  filesDetailModel: FilesVO = toFilesVO()

  filesDetailInfo() {
    this.filesStore.pkVo(this.$toParam<FilesQO>({ id: this.filesListSelectData[0].id } as FilesQO)).then((res: Res<FilesVO>) => {
      if (res.succ) {
        this.filesDetailModel = { ...res.data[0] }
        this.filesDetailDrawerVisible = true
      } else {
        this.$message.error(res.msg, 6)
      }
    })
  }

  filesDetailUpdate() {
    this.filesStore.pk(this.$toParam<FilesQO>({ id: this.filesDetailModel.id } as FilesQO)).then((res: Res<Files>) => {
      if (res.succ) {
        this.filesFormReset()
        this.filesFormModel = { ...res.data[0] }
        this.filesDetailDrawerVisible = false
        this.filesEditDrawerVisible = true
      } else {
        this.$message.error(res.msg, 6)
      }
    })
  }

  mounted() {
    this.filesListGetDataSet()
  }

}
</script>

<style scoped lang="less">

</style>
